package org.pine.start.filter;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.pine.common.beans.LogId;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;

import java.io.IOException;

/**
 * logid过滤器
 *
 * @author pine
 * @version v1.0
 * @since 2025-04-28 21:36
 */
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class LogIdFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        // 包装请求
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);

        String logId = requestWrapper.getHeader(LogId.LOG_ID_KEY);
        if (StrUtil.isBlank(logId)) {
            LogId.get();
        } else {
            LogId.put(logId);
        }

        try {
            // 继续执行
            filterChain.doFilter(request, response);
        } finally {
            LogId.remove();
        }
    }
}
